package com.yc.resfoods.controller;

import com.yc.resfoods.config.JwtTokenUtil;
import com.yc.resfoods.model.JwtResponse;
import com.yc.resfoods.service.JwtUserDetailsService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName JwtAuthenticationController
 * @since: 2023/8/21 10:04
 * @auth: kirito
 * @description:
 *
 **/
@RestController
@Slf4j
@RequestMapping("ressecurity/resfood")
@Api(tags = "用户登录授权管理")
public class JwtAuthenticationController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private JwtUserDetailsService userDetailsService;

    @GetMapping(value = {"hello"})
    public Claims test(@RequestHeader("Authorization") String bearerToken) {
        System.out.println("接受token为：" + bearerToken);
        String token = bearerToken.substring(7);
        Claims c = jwtTokenUtil.getAllClaimFromToken(token);
        return c;
    }

    @ApiOperation(value = "用户登陆操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "pwd", value = "密码", required = true)
    })
    @RequestMapping(value = "resuser.action", method = {RequestMethod.POST,RequestMethod.GET})
    public ResponseEntity<?> createAuthenticationToken(String username, String pwd) throws Exception {
        authenticate(username,pwd);
        final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        final String token = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(new JwtResponse(token));
    }

    private void authenticate(String username, String pwd) throws Exception {
        try {
            //调用认证管理器  对输入的用户名和密码进行验证
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, pwd));
        }catch (DisabledException e) {
            throw new Exception("USER_DISABLED", e);
        }catch (BadCredentialsException e) {
            throw new Exception("INVALID_CREATEDENTITALS", e);
        }
    }
}
